<script setup lang="ts">
import {ref} from "vue";
import {getCurrentInstance} from "vue";

//勾选协议（
const agreeProtocol = ref(false);

// 注册类型：user 或 admin
const roleType = ref('user')
//管理员口令
const adminToken = ref('')


//注册信息
const signInfo = ref({
  username: '',
  phone: '',
  password: '',
  twicePassword: '',
  email: '',
  role: 'user',  // 默认选中“用户”
})


const formRef = ref(); // 必须和 ref="formRef" 对应
const global = getCurrentInstance().appContext.config.globalProperties;


const handleSign = () => {
  formRef.value.validate(valid => {
    signInfo.value.role = roleType.value;

    if (!valid) {
      global.$message.warning('请完善注册信息');
      return;
    }
    if (signInfo.value.role === 'admin' && !adminToken.value) {
      global.$message.warning('请输入管理员口令');
      return;
    }
    global.$http({
      url: '/backend/sign',
      method: 'POST',
      data: {
        username: signInfo.value.username,
        password: signInfo.value.password,
        phone: signInfo.value.phone,
        email: signInfo.value.email,
        role: signInfo.value.role,
        adminToken: adminToken.value
      }
    }).then(res => {
      if (res.data.code === 200) {
        global.$message.success(res.data.msg || '注册成功');
        global.$router.push('/');
      } else {
        global.$message.error(res.data.msg || '注册失败');
      }
    }).catch(() => {
      global.$message.error('服务器错误，请稍后再试');
    });
  });
};


const rules = {
  username: [
    {required: true, message: '用户名不能为空', trigger: 'blur'},
    { min:2,max:10, message: '用户名长度在2到10个字符之间', trigger: 'blur' },
  ],
  password:[
    {required:true,message:'必须输入密码', trigger: 'blur'},
    { min:6,max:16, message: '密码长度在6到16个字符之间,不允许包含特殊符号', trigger: 'blur' },
    {
      pattern: /^[A-Za-z0-9!@#$%^&*_]{6,16}$/,
      message: '密码长度在6到16个字符之间,可包含!@#$%^&*_等符号',
      trigger: 'blur'
    }
  ],
  twicePassword: [
    {required: true, message: '再次输入密码', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        if (value !== signInfo.value.password) {
          callback(new Error('两次输入的密码不一样'));
        } else {
          callback()
        }
      },
      trigger: 'blur'
    },
  ],
  phone: [
    { required: true, message: '手机号不能为空', trigger: 'blur' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的11位手机号',
      trigger: 'blur'
    }
  ],
  email:[
    {required:true,message:'邮箱号不能为空', trigger: 'blur'},
    {
      type: 'email',
      message: '请输入正确的邮箱地址',
      trigger: ['blur','change']
    }
  ],
    role: [
      { required: true, message: '请选择身份类型', trigger: 'change' }
    ]
}

</script>

<template>
<!--头部信息-->
  <div class="header">
    <!--返回-->
     <router-link :to="'/'" class="header-back">
       <el-icon class="close-icon"><ArrowLeft /></el-icon>
       <span>返回首页</span>
     </router-link>

    <!--更多-->
    <el-dropdown>
    <span class="el-dropdown-link">
      更多
      <el-icon class="el-icon--right">
        <arrow-down />
      </el-icon>
    </span>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item>帮助中心</el-dropdown-item>
          <el-dropdown-item>意见反馈</el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>

  <!--注册信息-->
  <div class="user-info">

    <span>注册信息</span>
    <!-- 注册表单 -->
    <el-form class="sign-info"
             :model="signInfo"
             :rules="rules"
             ref="formRef">
        <el-form-item prop="username">
          <!-- 用户名 -->
          <el-input
            v-model="signInfo.username"
            placeholder="请输入用户名"
            prefix-icon="User"/>
        </el-form-item>

      <!-- 密码 -->
      <el-form-item prop="password">
        <el-input
            v-model="signInfo.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
        />
        </el-form-item>

        <el-form-item prop="twicePassword">
        <el-input
            v-model="signInfo.twicePassword"
            type="password"
            placeholder="请再次输入密码"
            prefix-icon="Lock"
            show-password
        />
        </el-form-item>

        <el-form-item prop="phone">
        <el-input
            v-model="signInfo.phone"
            placeholder="请输入手机号码（11位）"
            prefix-icon="Iphone"
        />
        </el-form-item>

        <el-form-item prop="email">
        <el-input
            v-model="signInfo.email"
            placeholder="请输入您的电子邮件"
            prefix-icon="Message"
        />
        </el-form-item>
      <!-- 身份选择 -->
      <el-form-item label="身份选择" prop="role">
        <el-radio-group v-model="roleType">
          <el-radio label="user">普通用户</el-radio>
          <el-radio label="admin">管理员</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 管理员口令，仅在选中管理员时显示 -->
      <el-form-item v-if="roleType === 'admin'" label="管理员口令">
        <el-input
            v-model="adminToken"
            placeholder="请输入管理员口令"
            prefix-icon="Key"
            type="password"
            show-password
        />
      </el-form-item>


      <el-form-item>
        <el-button :disabled="!agreeProtocol"
                   @click="handleSign"
                   class="sign-button">
          注册
        </el-button>
      </el-form-item>


        <el-form-item>
          <el-checkbox v-model="agreeProtocol">
            我已阅读用户协议
          </el-checkbox>
        </el-form-item>

    </el-form>
  </div>

</template>

<style scoped>
.header {
  display: flex;
  width: 100%;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-back {
  display: flex;
  align-items: center;
  font-size: 14px;

  text-decoration: none !important;
  color: inherit !important;

}

.close-icon {
  font-size: 18px;
  color: black;
}

.sign-info {
  text-align: center;
  margin-bottom: 30px;
}

.user-info {
  text-align: center;
  margin-bottom: 30px;
}

</style>